<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../../layui/css/layui.css">
    <link rel="stylesheet" href="../../layui/css/formSelects-v4.css">
    <script src="../../layui/layui.js"></script>
    <script src="../../js/jquery.min.js"></script>
</head>
<body>
<h2>用户列表</h2>
<hr/>
<form action="" class="layui-form">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
                <input type="text" id="username" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">用户角色</label>
            <div class="layui-input-inline" style="width: 400px;">
                <select id="roles" xm-select="roles">
                    <option value="-1">请选择</option>
                </select>
            </div>
        </div>
        <button type="button" class="layui-btn" onclick="reloadData()" lay-submit="" lay-filter="demo1">查询</button>

    </div>
</form>



<table class="layui-hide" id="userList" lay-filter="userTable"></table>
<script>
    $.get("http://localhost:9999/Role/all",function(data){
        $.each(data,function(){
            var opt = $("<option></option>").appendTo("#roles");
            opt.text(this.roleName).val(this.roleId);
        });
       /* layui.formSelects.render();*/
    });
</script>
<script src="../../js/config.js"></script>
<script>
    var table ;
    function reloadData(){
        var roleIds = layui.formSelects.value('roles','val');
        //执行重载
        table.reload('userList', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: {
                userName : $("#username").val(),
                "cha":roleIds.join(",")
            }
        });
    }

    layui.config({
        base: '../../layui/'
    }).extend({
        formSelects: 'formSelects-v4'
    });

    layui.use(['table','form','formSelects'], function(){
        table = layui.table;
        var form = layui.form;
        var select = layui.formSelects;

        table.render({
            elem: '#userList'
            ,url:'http://localhost:9999/kmsuser/all'
            ,page: true
            ,even : true
            ,id : "userList"
            ,toolbar:"#toolbarDemo",
            defaultToolbar: []
            ,cols: [[
                {field:'hello',type:'checkbox'}
                ,{field:'userId', title: '编号'}
                ,{field:'userName', title: '用户名'}
                ,{field:'photo',  title: '照片', sort: true}
                ,{field:'garden_list',  title: '所属园所',templet:function (d) {
                        if (d.garden_list == null){
                            return ' * ';
                        }
                        return d.garden_list.glName;
                    }}
                ,{field:'locked', title: '是否锁定', sort: true,templet:'#shifou'}
                ,{field:'kmsRoles',  title: '角色名称', templet:function(d){
                        if(d.kmsRoles.length == 0){
                            return "-";
                        }
                        let str = "";
                        for(let role of d.kmsRoles){
                            str += role.roleName + " ";
                        }
                        return str;
                    }},
                {toolbar: '#barDemo'}
            ]]
        });

        //监听行内的工具条
        table.on('tool(userTable)',function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'del'){ //删除
                layer.confirm('确认删除吗？', function(index){
                    layer.close(index);
                    $.post("http://localhost:9999/kmsuser/delete",{id:data.userId},function(d){
                        table.reload("userList");

                    });
                });
            }else if (layEvent === 'edit'){//TODO 编辑
                $.get('tianjia.html?_'+new Date().getTime(),function (s) {
                    layer.open({
                        type : 1,
                        title : '修改',
                        area:'800px',
                        content:s,
                        btn : ['确定','取消'],
                        success:function(){
                            form.render();
                            var rids = [];
                            for(let role of data.kmsRoles){
                                rids.push(role.roleId);
                            }
                            setTimeout(function () {
                                $("#roles_add").val(rids)
                            },100)
                            setTimeout(function () {
                                form.render();
                            },100)
                            //对表单回填数据
                            data.locked = data.locked == 0 ? null : data.locked;
                           /* data.glId = data.garden_list.glId;*/
                           /* console.log(data);*/
                            form.val('userForm',data);
                            $("#zhaopian").attr("src","/images/user/"+data.photo);
                           /* $(":radio[name='glId'][value='"+data.glId+"']").attr("checked",true);*/
                            var time = setInterval(function () {
                                if ($("#glId option").length >=1){
                                  /*  console.log(data.glId)*/
                                    clearInterval(time)
                                    $("#glId").val(data.garden_list.glId);
                                    layui.form.render()

                                }
                            },200)
                        },
                        yes : function () {
                            var str = $("#add_user_form").serialize();
                            $.get("http://localhost:9999/kmsuser/update",str,function () {
                                layer.close(layer.index);
                                table.reload('userList');
                            })
                        }
                    })
                })
            } else if (layEvent === 'detail'){ //TODO 查看详情

            }
        });
        //头工具栏事件
        table.on('toolbar(userTable)', function(obj){
            var h = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'batchDelete': //批量删除
                    var data = h.data;
                    if(data.length==0){
                        layer.msg("请选择要删除的内容");
                        return;
                    }
                    layer.confirm("要删除吗",function () {
                        var shan = "?";
                        for(let i of data){
                            shan+=`id=${i.userId}&`;
                        }
                        $.get(`http://localhost:9999/kmsuser/batchDelete${shan}`,function () {
                            layer.close(layer.index);
                            table.reload('userList');
                        });
                    });

                    break;
                case 'add':
                    $.get("tianjia.html",function (data) {
                        layer.open({
                            type : 1,
                            title : '添加用户',
                            skin : 'layui-layer-molv',
                            anim:1,
                            area : '800px',
                            content : data,
                            btn : ['确定','取消'],
                            success:function(){
                                setTimeout(function () {
                                    form.render();
                                },1000)

                            },
                            yes : function () {
                                var str = $("#add_user_form").serialize();
                                console.log(str)
                                $.post(`${new Config().base_url}/kmsuser/add`,str,function (data) {
                                    layer.close(layer.index);
                                    table.reload('userList');
                                });
                            }
                        })

                    });
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;
            };
        });

    });
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-circle"></i> 添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="batchDelete"><i class="layui-icon layui-icon-delete"></i> 批量删除</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a lay-event="edit"><i class="layui-icon layui-icon-edit"></i></a>
    <a href="javascript:void(0)" lay-event="del"><i class="layui-icon layui-icon-delete"></i></a>
</script>

<script type="text/html" id="shifou">
    <input type="checkbox" name="locked" value="{{d.locked}}" title="启用" lay-filter="roleTable" {{d.locked == 1 ? 'checked' : ''}}>
</script>


</body>
</html>